package org.jeecg.modules.hc.controller;

import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.hc.constant.RedisConstant;
import org.jeecg.modules.hc.entity.HcSiteAddressDetails;
import org.jeecg.modules.hc.entity.HcUser;
import org.jeecg.modules.hc.service.IHcSiteAddressDetailsService;
import org.jeecg.modules.hc.service.IHcUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

/**
 * @Description: 用户
 * @Author: jeecg-boot
 * @Date: 2022-12-13
 * @Version: V1.0
 */
//@Api(tags = "用户")
//@RestController
//@RequestMapping("/hc/hcUser")
@Slf4j
public class HcUserController extends JeecgController<HcUser, IHcUserService> {
    @Autowired
    private IHcUserService hcUserService;

    @Autowired
    private IHcSiteAddressDetailsService hcSiteAddressDetailsService;

    @Autowired
    private RedisUtil redisUtil;

    @ApiOperation("设置微信openId")
    @GetMapping("/setOpenId")
    public Result<?> setOpenId(@RequestParam String code) throws WxErrorException {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        hcUserService.setOpenId(code, sysUser.getId());
        return Result.ok();
    }

    /**
     * 在登陆页面，用户输入手机号，点击 【验证码】 按钮，调用此接口，该接口使用 SMS 服务平台提供的接口，先向SMS服务平台发送 短信内容和接收短信的用户的手机号
     * 由SMS 服务平台，向客户的手机发送短信
     * @param phone 用户在登录页面输入的，用户自己的用来接收验证码的手机号
     * @return 当同步调用 SMS平台接口，当调用的SMS平台接口返回成功后，向登录页面返回 验证码发送成功；
     * @throws UnsupportedEncodingException
     * @throws ClientException
     */
    @ApiOperation("发送验证码")
    @GetMapping("/sendSms")
    public Result<?> sendSms(@RequestParam String phone) throws UnsupportedEncodingException, ClientException {
        hcUserService.sendSms(phone);
        return Result.ok();
    }

//    @ApiOperation("获取当天浏览量")
//    @GetMapping("/getDayViews")
//    public Result<?> getDayViews() {
//        String yyyyMMdd = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//        String redisKey = RedisConstant.HC_DAY_VIEWS + yyyyMMdd;
//        int i = 0;
//
//        if (redisUtil.hasKey(redisKey)) {
//            i = (int) redisUtil.get(redisKey);
//        }
//
//        return Result.ok(i);
//    }
//
//    /**
//     * 每当用户打开一次 点餐页面 链接，即统计一次，即统计 PV 值
//     * 只是将 redis中的 hc_day_views_yyyy-MM-dd 的值 加 1
//     * @return
//     */
//    @ApiOperation("统计当天浏览量")
//    @GetMapping("/countDayViews")
//    public Result<?> countDayViews() {
//        String yyyyMMdd = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//
//        String redisKey = RedisConstant.HC_DAY_VIEWS + yyyyMMdd;
//
//        if (redisUtil.hasKey(redisKey)) {
//            redisUtil.incr(redisKey, 1);
//        } else {
//            // 第一个用户打开链接时，创建kv对，并将有效期设置为 24 小时；
//            redisUtil.set(redisKey, 1, 60 * 60 * 24);
//        }
//
//        return Result.ok();
//    }

    @ApiOperation("校验用户保存的地址是否在系统中存在或者被更改")
    @GetMapping("/checkAddress")
    public Result<?> checkAddress(@RequestParam String addressId) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        HcUser hcUser = hcUserService.getById(sysUser.getId());
        HcSiteAddressDetails hcSiteAddressDetails = hcUserService.checkAddress(hcUser);

        //判断用户保存的地址id和首页选择的地址id是否一致，不一致则把用户地址信息设置成空并返回
        if (!addressId.equals(hcSiteAddressDetails.getId())) {
            hcUser.setAddressId("");
        }

        hcUserService.setWalletBalance(hcUser);
        return Result.ok(hcUser);
    }

    @ApiOperation("保存地址信息")
    @PostMapping("/setAddress")
    public Result<?> setAddress(@RequestBody HcUser param) {
        if (StringUtils.isBlank(param.getAddressId())
                || StringUtils.isBlank(param.getNameTakingMeal())
                || StringUtils.isBlank(param.getPhoneTakingMeals())
                || StringUtils.isBlank(param.getSupplyAddressName())
                || StringUtils.isBlank(param.getSupplyAddressCode())
        ) {
            return Result.error("参数错误");
        }

        HcSiteAddressDetails hcSiteAddressDetails = hcSiteAddressDetailsService.getById(param.getAddressId());

        if (hcSiteAddressDetails == null) {
            return Result.error("未查询到地址");
        }

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        hcUserService.updateById(new HcUser().setId(sysUser.getId())
                .setAddressId(param.getAddressId())
                .setNameTakingMeal(param.getNameTakingMeal())
                .setPhoneTakingMeals(param.getPhoneTakingMeals())
                .setSupplyAddressName(param.getSupplyAddressName())
                .setSupplyAddressCode(param.getSupplyAddressCode())

                //panjixiang
                .setSupplyHomeCode(param.getSupplyHomeCode())
                .setAddressLatitude(hcSiteAddressDetails.getLatitude())
                .setAddressLongitude(hcSiteAddressDetails.getLongitude())
        );

        return Result.ok(param);
    }

    @ApiOperation("登录")
    @GetMapping("/login")
    public Result<?> login(@RequestParam String phone, String smsCode) {
        return Result.ok(hcUserService.login(phone, smsCode));
    }

    /**
     * 功能描述：
     *      当用户打开微信小程序时，小程序端调用 wx.login() 方法，从微信平台获取一个由微信平台生成的，只能使用一次的 code
     *  后端服务以code作为接口调用参数，向微信平台发送请求，请求获取用户的 open_id 和 access_token，access_token 只有2小时有效期，该access_token 主要是给 小程序端用来调用 wx.xxxx() 接口的
     *  本方法返回的token，是业务系统自己生成的token，仅包含了 openid，没有包含 微信平台返回的，可以调用微信接口的 access_token；
     *
     * @param code 小程序端调用 wx.login() 接口从 微信平台获取到的一次性的code
     * @return JWT 格式的字符串，格式为 {"alg":"HMAC256","typ":"JWT"}.{"username":"hc_user_login_token_<openid>"}.HMAC256(xxx)
     * @throws Exception
     */
//    @ApiOperation("登录")
//    @GetMapping("/loginForWx")
    public Result<?> loginForWx(@RequestParam String code) throws Exception {
        return Result.ok(hcUserService.loginForWx(code));
    }

    /**
     * 分页列表查询
     *
     * @param hcUser
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "用户-分页列表查询")
//    @ApiOperation(value = "用户-分页列表查询", notes = "用户-分页列表查询")
//    @GetMapping(value = "/list")
    public Result<IPage<HcUser>> queryPageList(HcUser hcUser,
                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                               HttpServletRequest req) {
        QueryWrapper<HcUser> queryWrapper = QueryGenerator.initQueryWrapper(hcUser, req.getParameterMap());
        Page<HcUser> page = new Page<HcUser>(pageNo, pageSize);
        IPage<HcUser> pageList = hcUserService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param hcUser
     * @return
     */
//    @AutoLog(value = "用户-添加")
//    @ApiOperation(value = "用户-添加", notes = "用户-添加")
    //@RequiresPermissions("org.jeecg.modules:hc_user:add")
//    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody HcUser hcUser) {
        hcUserService.save(hcUser);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param hcUser
     * @return
     */
//    @AutoLog(value = "用户-编辑")
//    @ApiOperation(value = "用户-编辑", notes = "用户-编辑")
    //@RequiresPermissions("org.jeecg.modules:hc_user:edit")
//    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody HcUser hcUser) {
        hcUserService.updateById(hcUser);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
//    @AutoLog(value = "用户-通过id删除")
//    @ApiOperation(value = "用户-通过id删除", notes = "用户-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:hc_user:delete")
//    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        hcUserService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
//    @AutoLog(value = "用户-批量删除")
//    @ApiOperation(value = "用户-批量删除", notes = "用户-批量删除")
    //@RequiresPermissions("org.jeecg.modules:hc_user:deleteBatch")
//    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hcUserService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "用户-通过id查询")
    @ApiOperation(value = "用户-通过id查询", notes = "用户-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<HcUser> queryById(@RequestParam(name = "id", required = false) String id) {
        if (StringUtils.isBlank(id)) {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            id = sysUser.getId();
        }

        HcUser hcUser = hcUserService.getById(id);

        if (hcUser == null) {
            return Result.error("未找到对应数据");
        }

        hcUserService.setWalletBalance(hcUser);
        return Result.OK(hcUser);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hcUser
     */
    //@RequiresPermissions("org.jeecg.modules:hc_user:exportXls")
//    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HcUser hcUser) {
        return super.exportXls(request, hcUser, HcUser.class, "用户");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("hc_user:importExcel")
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HcUser.class);
    }

}
